<template xmlns:el-col="http://www.w3.org/1999/html">
    <div>
        <!--客户管理头部-->
        <el-row class="head">
            <el-col :span="24">
                <h1 class="contract_title" >我的仪表盘</h1>
                <span>/ 详细的工作和业绩报表</span>
            </el-col>
        </el-row>
        <!--卡片-->
        <el-row class="cardBox">
            <el-col :span="6">
                <el-card class="box-card" style="background-color: #1CAF9A;">
                    <div class="pictu"><i class="iconfont icon-kehu1 icon" ></i></div>
                    <div class="text"><div>客户总量</div><div class="item">{{this.cusNum}}</div></div>
                    <el-row class="colorchange">
                        <el-col :span="12">
                            <div>机会客户数量</div><div class="it">{{this.oppoNum}}</div>
                        </el-col>
                        <el-col :span="12">
                            <div>成交客户数量</div><div class="it">{{this.successCus}}</div>
                        </el-col>
                    </el-row>

                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="box-card" style="background-color: #D9534F;">
                    <div class="pictu"><i class="iconfont icon-yewujihui icon" ></i></div>
                    <div class="text"><div>销售机会成功率</div><div class="item">{{oppoPie*100}}%</div></div>
                    <el-row class="colorchange">
                        <el-col :span="8">
                            <div>在跟</div><div class="it">{{oppoFollow}}</div>
                        </el-col>
                        <el-col :span="8">
                            <div>灭失</div><div class="it">{{oppoNotOn}}</div>
                        </el-col>
                        <el-col :span="8">
                            <div>成功</div><div class="it">{{oppoSuccee}}</div>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="box-card" style="background-color: #428bca;">
                    <div class="pictu"><i class="iconfont icon-xiaoshoufenxi icon" ></i></div>
                    <div class="text"><div>今年销售额</div><div class="item">{{saleroomYear}}</div></div>
                    <el-row class="colorchange">
                        <el-col :span="12">
                            <div>本月销售额</div><div class="it">{{saleroomThisMonth}}</div>
                        </el-col>
                        <el-col :span="12">
                            <div>上月销售额</div><div class="it">{{saleroomBeforMonth}}</div>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="box-card" style="background-color: #F0AD4E;">
                    <div class="pictu"><i class="iconfont icon-dangrixiaoshoue icon" ></i></div>
                    <div class="text"><div>今年回款额</div><div class="item">{{returnedMoneyThisYear}}</div></div>
                    <el-row class="colorchange">
                        <el-col :span="12">
                            <div>本月回款额</div><div class="it">{{returnedMoneyThisMonth }}</div>
                        </el-col>
                        <el-col :span="12">
                            <div>上月回款额</div><div class="it">{{ returnedMoneyBeforMonth }}</div>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>
        <!--e-charts-->
        <el-row>
            <el-col :span="16">
                <div class="content">
                    <div class="charts"  ref="chart1"> </div>
                </div>
            </el-col>
            <el-col :span="8">
                <div class="content">
                    <div class="charts"  ref="chart2"> </div>
                </div>
            </el-col>
        </el-row>

        <!--表格-->
        <el-row>
            <el-col :span="10">
                <div class="content">
                    <el-row class="bar-title">
                        <el-col style="height:25px" :span="20">
                            本月销售Top 10
                        </el-col>
                    </el-row>
                    <div class="statable">
                        <el-table border height="200" :data="contractGroupByEmp" >
                            <el-table-column prop="" type="index" width="70" header-align="center" align="center"></el-table-column>
                            <el-table-column prop="emp.empName" label="员工" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="saleroom" label="销售额" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="conNum" label="合同量" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="returnMoney" label="回款额" header-align="center" align="center"  ></el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="content">
                    <el-row class="bar-title">
                        <el-col style="height:25px" :span="20">
                            回款计划提醒
                            <span style="font-size: 12px;font-weight: normal">/ 根据应收日期列出到期但未收齐款项的合同</span>
                        </el-col>
                    </el-row>
                    <div class="statable">
                        <el-table border height="200" :data="returnmonNotReturn">
                            <el-table-column type="index" width="70" header-align="center" align="center"></el-table-column>
                            <el-table-column prop="contract.contractNum" width="150" label="合同编号" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="contract.customer.customerName" label="客户名称" header-align="center" align="center" show-overflow-tooltip ></el-table-column>
                            <el-table-column prop="contract.empSigner.empName" label="促成人员" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="returnMoney" label="回款金额" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="" label="预计时间" header-align="center" align="center"  >
                                <template slot-scope="s">{{ s.row.returnDate | format_date}}</template>
                            </el-table-column>
                            <el-table-column label="状态" align="center" header-align="center">
                                <template slot-scope="s">
                                    <span style="color:#F56C6C" v-if="new Date(s.row.returnDate) - new Date() < -1000*3600*24 ">已逾期</span>
                                    <span style="color:#E6A23C" v-if="new Date(s.row.returnDate) - new Date()>-1000*3600*24 && new Date(s.row.returnDate) - new Date() < 1000*3600*24*7">
                                        快到期了
                                    </span>
                                    <span style="color:#67C23A" v-if="new Date(s.row.returnDate) - new Date() > 1000*3600*24*7" >
                                        还早
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="170px">
                                <template slot-scope="s">
                                    <el-button type="primary" size="mini" @click="returnMon(s.row)">回款</el-button>
                                    <el-button type="danger" size="mini" @click="notRemind(s.row)">不在提醒</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-col>
            <el-col>
                <div class="content">
                    <el-row class="bar-title">
                        <el-col style="height:25px" :span="20">
                            最近签订的合同
                        </el-col>
                        <el-button type="text" size="mini" style="float:right;margin-right:10px;color:#909399;height:25px" @click="$router.push({path:'/contract-index'})">更多</el-button>
                    </el-row>
                    <div class="statable">
                        <el-table border :data="newContract">
                            <el-table-column type="index" width="70" header-align="center" align="center"></el-table-column>
                            <el-table-column prop="customer.customerName" label="客户名称" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="conState.name" label="合同状态" header-align="center" align="center"  ></el-table-column>
                            <el-table-column prop="" label="成交时间" header-align="center" align="center"  >
                                <template slot-scope="s">{{s.row.signTime | format_date}}</template>
                            </el-table-column>
                            <el-table-column prop="totalMoney" label="总金额额" header-align="center" align="center"  ></el-table-column>
                            <el-table-column label="回款金额" header-align="center" align="center">
                                <template slot-scope="s">
                                    {{ s.row.returnMoney?s.row.returnMoney:0 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="欠款金额" header-align="center" align="center">
                                <template slot-scope="scope">
                                    {{scope.row.totalMoney-scope.row.returnMoney}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="empSigner.empName" label="业务员" header-align="center" align="center"  ></el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    const echarts = require('echarts');
    export default {
        name: "myHome",
        data(){
            return{
                allContract:[],     // 合同数据源
                newContract:[],     // 最新的5条数据
                returnmonNotReturn:[],//获取回款计划提醒
                initChartTData:[],      //销售漏斗数据
                oppoNotOn:0,        //销售机会灭失数
                oppoFollow:0,       //销售机会在跟数
                oppoSuccee:0,       //销售机会成功数
                oppoPie:0,          //销售机会成功概率
                cusNum:0,//客户总量
                oppoNum:0,//机会客户数
                successCus:0//成交客户数
            }
        },
        methods:{
            // 不在提醒
            notRemind(row){
                this.global.confirm("提示","确认不在提醒？",
                () => {
                    row.isReturn = 3
                    const loading = this.$loading({
                        lock: true,
                        text: '保存中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0,0,0,0.5)'
                    });
                    this.axios.post("api/in-sale/return-mon",row)
                    .then(() => {
                        this.global.mes_success("修改成功")
                        loading.close()
                        this.get_all_contract()
                    })
                    .catch(() => {
                        this.global.mes_error("修改失败")
                    })
                },
                () => {
                    this.global.mes_message("取消回款")
                })

            },
            // 回款计划快捷回款
            returnMon(row){
                this.global.confirm("提示","确认回款？",
                async () => {
                    const res = await this.axios.get("api/in-sale/contract/"+row.contract.contractId)
                    const contract = res.data
                    let returnRecord = {				// 回款记录数据源
                        realReturnDate:new Date(),
                        takeInvoice:2,
                        paymentMethod:contract.paymentMethod,
                        principal:this.$store.state.user
                    }
                    // 将回款计划 加入记录中
                    returnRecord.returnmon = row
                    // 将合同 加入记录对象中
                    returnRecord.contract = contract
                    // 金额修改
                    returnRecord.returnMoney = row.returnMoney
                    const loading = this.$loading({
                        lock: true,
                        text: '保存中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0,0,0,0.5)'
                    });
                    this.axios.post("api/in-sale/returnRecord", returnRecord)
                    .then(res => {
                        loading.close()
                        this.global.mes_success("回款记录保存成功")
                        this.get_all_contract()
                    })
                    .catch(err => {
                        loading.close()
                        this.global.mes_error("回款记录保存失败，请稍后再试！")
                    })
                },() => {
                    this.global.mes_message("取消回款")
                })
            },
            initCharts1 () {
                let myChart = echarts.init(this.$refs.chart1);
            myChart.setOption({
                title: {
                    text: '销售业绩图',
                    /* subtext: '纯属虚构' */
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    bottom:10,
                    data: ['销售额', '回款额']
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar' ]},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '销售额',
                        type: 'bar',
                        data: this.saleroomYearMonth(),
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        }
                    },
                    {
                        name: '回款额',
                        type: 'bar',
                        data: this.returnedMoneyYearMonth(),
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        }
                    },
                ]
            });
            },
            initCharts2 () {
                let myChart = echarts.init(this.$refs.chart2);
                myChart.setOption( {
                    title:{
                        text: "销售漏斗"
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c}%"
                    },
                    toolbox: {
                        feature: {
                            dataView: {readOnly: false},
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    legend: {
                        bottom: 10,
                        data: ['准备推进','正在推进','已生成合同','待审核']
                    },

                    series: [
                        {
                            name:'漏斗图',
                            type:'funnel',
                            left: '10%',
                            top: 60,
                            //x2: 80,
                            bottom: 60,
                            width: '80%',
                            // height: {totalHeight} - y - y2,
                            min: 0,
                            max: 100,
                            minSize: '0%',
                            maxSize: '100%',
                            sort: 'descending',
                            gap: 2,
                            label: {
                                show: true,
                                position: 'inside'
                            },
                            labelLine: {
                                length: 10,
                                lineStyle: {
                                    width: 1,
                                    type: 'solid'
                                }
                            },
                            itemStyle: {
                                borderColor: '#fff',
                                borderWidth: 1
                            },
                            emphasis: {
                                label: {
                                    fontSize: 20
                                }
                            },
                            data:this.initChartTData,
                        }
                    ]
                })
            },
            /*客户总量*/
            getCuses(){
                this.axios.get("api/customer/select_cus")
                    .then(res => {

                        this.cusNum = res.data.length
                    }).catch(() => {
                    this.global.mes_error("获取数据失败！")
                })
            },
            /*机会客户数*/
            getOppoCus(){
                this.axios.get("api/customer/find-cusinfo",{params:{"currPage":1,"pageSize":99999,"search":'',"cusTypeName":'',"stageId":3}})
                        .then(res => {
                            this.oppoNum = res.data.total
                            console.log("res")
                            console.log(res.data)
                    }).catch(() => {
                    this.global.mes_error("获取数据失败！")
                })

            },
            /*成交客户数*/
            getSuccessCus(){
                this.axios.get("api/customer/find-cusinfo",{params:{"currPage":1,"pageSize":99999,"search":'',"cusTypeName":'',"stageId":5}})
                    .then(res => {
                        this.successCus = res.data.total
                    }).catch(() => {
                    this.global.mes_error("获取数据失败！")
                })
            },
            /* 获取全部合同数据 */
            get_all_contract(){
                this.axios.get("api/in-sale/contracts")
                .then(res => {
                    this.allContract = res.data
                    this.initCharts1();
                    this.initCharts2();
                })
                .catch(() => {
                    this.global.mes_error("获取数据失败！")
                })
                // 最新的5条数据
                this.axios.get("api/in-sale/newContract")
                .then(res => {
                    this.newContract = res.data
                })
                .catch(err => {
                    this.global.mes_error("获取数据失败！")
                })
                // 获取回款计划提醒
                this.axios.get("api/in-sale/returnmonNotReturn")
                .then(res => {
                    this.returnmonNotReturn = res.data
                })
                .catch(err => {
                    this.global.mes_error("获取数据失败！")
                })
            },
            // 一年分月销售额
            saleroomYearMonth(){
                const thisYear = new Date().getFullYear()
                let saleroom = [0,0,0,0,0,0,0,0,0,0,0,0]
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        saleroom[new Date(c.signTime).getMonth()] += c.totalMoney
                    }
                })
                return saleroom
            },
            // 一年分月回款额
            returnedMoneyYearMonth(){
                const thisYear = new Date().getFullYear()
                let saleroom = [0,0,0,0,0,0,0,0,0,0,0,0]
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        saleroom[new Date(c.signTime).getMonth()] += c.returnMoney
                    }
                })
                return saleroom
            },
            getAllOppo(){
                this.axios.get("api/oppo-sale/selectOppo")
                    .then(res=>{
                        let sumNum1 = 0;
                        let sumNum2 = 0;
                        let sumNum3 = 0;
                        let sumNum4 = 0;
                        res.data.forEach(oppo => {
                            if(oppo.is_on === 2){
                                sumNum1 = sumNum1 + 1;
                            }else if(oppo.oppo_state_id === 3){
                                sumNum2 = sumNum2 + 1;
                            }else{
                                sumNum3 =sumNum3 + 1;
                            }
                            sumNum4 = sumNum4 + 1
                        })
                        this.oppoNotOn = sumNum1;
                        this.oppoFollow = sumNum3;
                        this.oppoSuccee = sumNum2;
                        this.oppoPie = (sumNum2/sumNum4).toFixed(2)
                    }).catch()
            },
            //获取销售机会来画漏斗图
            get_all_opportunity(){
                this.axios.get("api/oppo-sale/oppoNoPage")
                    .then(res => {
                        window.console.log(res)
                        let sumNum1 = 0;
                        let sumNum2 = 0;
                        let sumNum3 = 0;
                        let sumNum4 = 0;
                        let sumNum = 0;
                        res.data.forEach(oppo => {
                            //准备推进
                            if (oppo.state.oppoStateId === 1){
                                sumNum1 = sumNum1 + 1;
                            }
                            //正在推进
                            else if(oppo.state.oppoStateId === 2){
                                sumNum2 = sumNum2 + 1;
                            }
                            //已生成合同
                            else if(oppo.state.oppoStateId === 3){
                                sumNum3 = sumNum3 + 1;
                            }
                            //待审核
                            else if(oppo.state.oppoStateId === 5){
                                sumNum4 = sumNum4 + 1;
                            }
                        });
                        sumNum = sumNum1+sumNum2+sumNum3+sumNum4
                        if(sumNum1 != 0){
                            this.initChartTData.push({value: (100*sumNum1/sumNum).toFixed(2), name: '准备推进'})
                        }
                        if(sumNum2 != 0){
                            this.initChartTData.push({value: (100*sumNum2/sumNum).toFixed(2), name: '正在推进'})
                        }
                        if(sumNum3 != 0){
                            this.initChartTData.push({value: (100*sumNum3/sumNum).toFixed(2), name: '已生成合同'})
                        }
                        if(sumNum4 != 0){
                            this.initChartTData.push({value: (100*sumNum4/sumNum).toFixed(2), name: '待审核'})
                        }
                    })
                    .catch(() => {
                        this.global.mes_error("获取销售机会数据失败！")
                    })
            },
        },
        created(){
            this. getCuses();
            this.getOppoCus();
            this. getSuccessCus();
            this.get_all_contract();
            this.get_all_opportunity();
            this.getAllOppo();
        },
        mounted() {
            this.initCharts1();
            this.initCharts2();
        },
        computed:{
            
            // 今年销售额
            saleroomYear(){
                // 计算今年 年份
                const thisYear = new Date().getFullYear()
                let total = 0
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){

                        total += c.totalMoney
                    }
                })
                if(total >= 100000){
                    total = (total/10000).toFixed(2) + "万"
                }
                return total
            },
            // 本月销售额
            saleroomThisMonth(){
                const thisMonth = new Date().getMonth()
                const thisYear = new Date().getFullYear()
                let total = 0
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        if(new Date(c.signTime).getMonth() == thisMonth){
                            total += c.totalMoney
                        }
                    }
                })
                if(total >= 100000){
                    total = (total/10000).toFixed(2) + "万"
                }
                return total
            },
            // 上月销售额
            saleroomBeforMonth(){
                const thisMonth = new Date().getMonth()-1
                const thisYear = new Date().getFullYear()
                let total = 0
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        if(new Date(c.signTime).getMonth() == thisMonth){
                            total += c.totalMoney
                        }
                    }
                })
                if(total >= 100000){
                    total = (total/10000).toFixed(2) + "万"
                }
                return total
            },
            // 今年回款
            returnedMoneyThisYear(){
                // 计算今年 年份
                const thisYear = new Date().getFullYear()
                let total = 0
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){

                        total += c.returnMoney
                    }
                })
                if(total >= 100000){
                    total = (total/10000).toFixed(2)+ "万"
                }
                return total
            },
            // 本月回款
            returnedMoneyThisMonth(){
                const thisMonth = new Date().getMonth()
                const thisYear = new Date().getFullYear()
                let total = 0
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        if(new Date(c.signTime).getMonth() == thisMonth){
                            total += c.returnMoney
                        }
                    }
                })
                if(total >= 100000){
                    total = (total/10000).toFixed(2) + "万"
                }
                return total
            },
             // 上月回款
            returnedMoneyBeforMonth(){
                const thisMonth = new Date().getMonth()-1
                const thisYear = new Date().getFullYear()
                let total = 0
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        if(new Date(c.signTime).getMonth() == thisMonth){
                            total += c.returnMoney
                        }
                    }
                })
                if(total >= 100000){
                    total = (total/10000).toFixed(2) + "万"
                }
                return total
            },
            // 合同根据员工分组，
            contractGroupByEmp(){
                const thisMonth = new Date().getMonth()
                const thisYear = new Date().getFullYear()
                let emps = []
                let tempArray = []
                // 筛选出本月的合同
                this.allContract.forEach(c => {
                    if(new Date(c.signTime).getFullYear() == thisYear){
                        if(new Date(c.signTime).getMonth() == thisMonth){
                            tempArray.push(c)
                        }
                    }
                })
                // 获取所有的员工
                let objArr=[]
                tempArray.forEach(ta => {
                    if(emps.indexOf(ta.empSigner.empId) < 0){
                        emps.push(ta.empSigner.empId)
                        let obj = []
                        obj.emp = ta.empSigner
                        obj.saleroom = ta.totalMoney?ta.totalMoney:0
                        obj.conNum = 1
                        obj.returnMoney = ta.returnMoney?ta.returnMoney:0
                        objArr.push(obj)
                    }else{
                        for (let obj of objArr) {
                            if (obj.emp.empId === ta.empSigner.empId){
                                obj.saleroom += ta.totalMoney
                                obj.conNum += 1
                                obj.returnMoney += ta.returnMoney
                                return
                            }
                        }
                    }
                })
                // 排序
                objArr.sort(function(a,b){return b.saleroom-a.saleroom});
               
                if(objArr.length>10){
                    objArr = objArr.slice(0,9)
                }
                return objArr
            }
        }
    }

</script>

<style scoped>
    .el-col span{
        color: #b4b4bc;
        margin-left: 8px;
    }
    .box-card{
        width: 300px;

    }
    .pictu{width: 65px;height: 65px;display: inline-block

    }
    .cardBox{margin: 20px;font-family: Microsoft YaHei, SimSun;font-size: 12px;

    }
    .el-col{
        position: relative;
    }
    .icon{
        font-size: 50px;color: #eeeeee;font-weight: bolder
    }
    .text{
        position: absolute;
        top: 18px;
        left: 100px;

    }
    .text div{
        color: #ffffff;

    }
    .item{
        color: #ffffff;
        text-align: center;
        font-size: 28px!important;
        padding-top: 5px;
    }
    .colorchange{
        color: #ffffff;
    }
    .it{
        font-size: 22px;
    }

    .content {margin: 0px 20px 10px 20px;background: #fcfbfd;min-height:10px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);}
    .charts{
        padding-top: 10px;
        width: 100%;
        min-height: 430px;

    }
    .statable{
        padding: 15px 20px;
        min-height: 200px;

    }
    .bar-title{
        padding: 10px;
        font-size: 15px;
        font-family: Microsoft YaHei, SimSun;
        color: #1D2939;
        font-weight: bolder;
        border-bottom: 1px solid #eeeeee;
    }
</style>